/* eslint-disable no-undef,no-param-reassign,import/named,consistent-return */
/**
 * Created by chengzhenfu on 2019/5/5.
 * Modified by  on .
 *axios 封装
 */
import baseURL from '@/configs/baseUrl'
import Axios from 'axios';
import router from '@/router/index';
import utils from '@/jslibs/utils'
    const fetch = Axios.create({
        withCredentials: false,
        baseURL,
        timeout: 20000, // 设置超时时间
    });
    let loading;
    //请求发送前拦截，根据地址重新配置域名，再子路由请求时必须加/ 例如：请求 localhost:80/app/inset  fetch.get('/app/inset');
    fetch.interceptors.request.use(function (config) {
        const token = utils.getCookie('token');
        config.headers = {'token': token || sessionStorage.getItem('token') || ''};
        loading = vm.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        if(config.params){
        	config.params.token = utils.getCookie('token');
        }
        if(config.data){
        	config.data.token = utils.getCookie('token');
        }
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });

    // 添加响应拦截器
    fetch.interceptors.response.use(function (response) {
        loading.close();
		if (response.data.code == "203") {
			utils.setCookie('token', "", -1);
			utils.removeSession('token');
			router.push('/login');
			vm.$message.warning(response.data.message);
		} else {
			return response;
		}	
    }, function (error) {
        // 对响应错误做点什么
       loading.close();
        const { status, data } = error.response;
        switch (status) {
          case 203:
			utils.setCookie('token', "", -1);
			utils.removeSession('token');
			router.push('/login');
			vm.$message.warning(data.error.message);
			break;
          case 500:
            vm.$message('系统繁忙');
            break;
          default:
            vm.$message('系统繁忙');
            return Promise.reject(data);
        }
    });

export default fetch;